// composables/useResponsiveLayout.ts
import { ref, computed, onMounted, onUnmounted } from 'vue'

export interface ResponsiveLayoutConfig {
  breakpoints: {
    [key: string]: number // 断点名称: 最小宽度
  }
  itemsPerRow: {
    [key: string]: number // 断点名称: 每行显示数量
  }
  defaultRows?: number // 默认显示行数
}

export interface ResponsiveLayoutResult {
  containerWidth: Ref<number>
  currentBreakpoint: ComputedRef<string>
  itemsPerRow: ComputedRef<number>
  calculatePageSize: (rows?: number) => number
  calculateItemsPerRow: (containerWidth: number) => number
}

export function useResponsiveLayout(
  containerRef: Ref<HTMLElement | null>,
  config: ResponsiveLayoutConfig
): ResponsiveLayoutResult {
  const containerWidth = ref(0)
  
  // 默认配置
  const defaultConfig: ResponsiveLayoutConfig = {
    breakpoints: {
      xs: 0,
      sm: 576,
      md: 768,
      lg: 992,
      xl: 1200,
      xxl: 1440,
      xxxl: 1920
    },
    itemsPerRow: {
      xs: 1,
      sm: 2,
      md: 3,
      lg: 4,
      xl: 5,
      xxl: 5,
      xxxl: 6
    },
    defaultRows: 3
  }
  
  const mergedConfig = { ...defaultConfig, ...config }
  
  // 计算当前断点
  const currentBreakpoint = computed(() => {
    const breakpoints = Object.entries(mergedConfig.breakpoints)
      .sort(([, a], [, b]) => b - a) // 从大到小排序
    
    for (const [breakpoint, minWidth] of breakpoints) {
      if (containerWidth.value >= minWidth) {
        return breakpoint
      }
    }
    return 'xs'
  })
  
  // 计算每行显示数量
  const itemsPerRow = computed(() => {
    return mergedConfig.itemsPerRow[currentBreakpoint.value] || 1
  })
  
  // 计算每页显示数量（行数的整数倍）
  const calculatePageSize = (rows?: number): number => {
    const rowCount = rows || mergedConfig.defaultRows || 3
    return itemsPerRow.value * rowCount
  }
  
  // 根据容器宽度计算每行显示数量
  const calculateItemsPerRow = (width: number): number => {
    const breakpoints = Object.entries(mergedConfig.breakpoints)
      .sort(([, a], [, b]) => b - a)
    
    for (const [breakpoint, minWidth] of breakpoints) {
      if (width >= minWidth) {
        return mergedConfig.itemsPerRow[breakpoint] || 1
      }
    }
    return 1
  }
  
  // 更新容器宽度
  const updateContainerWidth = () => {
    if (containerRef.value) {
      containerWidth.value = containerRef.value.clientWidth
    }
  }
  
  // 防抖resize处理
  let resizeTimer: number | null = null
  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = window.setTimeout(() => {
      updateContainerWidth()
    }, 100)
  }
  
  onMounted(() => {
    updateContainerWidth()
    window.addEventListener('resize', handleResize)
  })
  
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  })
  
  return {
    containerWidth,
    currentBreakpoint,
    itemsPerRow,
    calculatePageSize,
    calculateItemsPerRow
  }
}